package com.t4.wechat.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.t4.auth.service.SysUserService;
import com.t4.common.exception.T4Exception;
import com.t4.common.jwt.JwtHelper;
import com.t4.common.result.Result;
import com.t4.model.system.SysUser;
import com.t4.vo.wechat.BindPhoneVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;

@Api(tags = "")
@Controller
@RequestMapping("/admin/wechat")
@CrossOrigin // 跨域
public class WechatController {

    @Resource
    private WxMpService wxMpService;

    @Resource
    private SysUserService sysUserService;

    @Value("${wechat.userInfoUrl}")
    private String userInfoUrl;

    @ApiOperation(value = "获取回调路径")
    @GetMapping("authorize")
    public String authorize(@RequestParam("returnUrl") String returnUrl,
                            HttpServletRequest request){
        // buildAuthorizationUrl包含三个参数
        // 参数一：授权路径，在哪个路径获取微信信息
        // 参数二：固定值，授权类型
        // 参数三：授权成功后的跳转路径
        String redirectURL = null;
        try {
            redirectURL = wxMpService.getOAuth2Service().buildAuthorizationUrl(
                    userInfoUrl,
                    WxConsts.OAuth2Scope.SNSAPI_USERINFO,
                    URLEncoder.encode(returnUrl.replace("t4oa", "#"), "utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "redirect:" + redirectURL;
    }


    @GetMapping("userInfo")
    public String userInfo(@RequestParam("code") String code,
                           @RequestParam("state") String returnUrl) throws WxErrorException {
        // 1. 获取accessToken
        WxOAuth2AccessToken accessToken = wxMpService.getOAuth2Service().getAccessToken(code);

        // 2. 使用accessToken获取openId
        String openId = accessToken.getOpenId();
        // 获取微信用户信息
        WxOAuth2UserInfo wxMpUser = wxMpService.getOAuth2Service().getUserInfo(accessToken, null);

        // 3. 根据openId查询用户表，判断是否绑已经绑定
        SysUser sysUser = sysUserService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getOpenId, openId));
        // 3.1 已经绑定成功
        String token = "";
        if(sysUser != null){
            // 生成token
            HashMap<String, Object> tokenClaims = new HashMap<>();
            tokenClaims.put("userId", sysUser.getId());
            tokenClaims.put("username", sysUser.getUsername());
            token = JwtHelper.createToken(tokenClaims);
        }
        // 3.2 未绑定，进行绑定
        if(returnUrl.indexOf("?") == -1) {
            return "redirect:" + returnUrl + "?token=" + token + "&openId=" + openId;
        } else {
            return "redirect:" + returnUrl + "&token=" + token + "&openId=" + openId;
        }
    }

    @ApiOperation(value = "微信绑定手机号")
    @PutMapping("bindPhone")
    @ResponseBody
    public Result bindPhone(@RequestBody BindPhoneVo bindPhoneVo){
        SysUser sysUser = sysUserService.getOne(
                new LambdaQueryWrapper<SysUser>().
                        eq(SysUser::getPhone, bindPhoneVo.getPhone()));
        if(sysUser != null){
            sysUser.setOpenId(bindPhoneVo.getOpenId());
            sysUserService.updateById(sysUser);
            HashMap<String, Object> tokenClaims = new HashMap<>();
            tokenClaims.put("userId", sysUser.getId());
            tokenClaims.put("username", sysUser.getUsername());
            String token = JwtHelper.createToken(tokenClaims);
            return Result.success(token);
        }else{
            throw new T4Exception(2016, "手机号码不存在，绑定失败");
        }
    }
}
